package com.aqie.meet.ui.find;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;

import com.aqie.libcommon.adapter.CommonAdapter;
import com.aqie.libcommon.adapter.CommonViewHolder;
import com.aqie.libcommon.app.BaseFragment;
import com.aqie.libcommon.utils.CommonUtils;
import com.aqie.libcommon.utils.SimpleJsonTool;
import com.aqie.libcommon.view.EmptyView;
import com.aqie.libfactory.model.api.PageList;
import com.aqie.libfactory.model.api.RspModel;
import com.aqie.libfactory.model.api.post.FindPost;
import com.aqie.libfactory.net.Network;
import com.aqie.libfactory.net.RemoteService;
import com.aqie.libnavanotation.FragmentDestination;
import com.aqie.meet.R;
import com.aqie.meet.utils.TimeUtils;
import com.aqie.meet.utils.Utils;
import com.aqie.meet.view.AImageView;

import java.util.ArrayList;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.lifecycle.ViewModelProviders;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;
import butterknife.OnClick;
import circletextimage.viviant.com.circletextimagelib.view.CircleTextImage;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

@FragmentDestination(pageUrl = "main/tabs/find", asStarter = false,needLogin = true)
public class FindFragment extends BaseFragment {


    private FindViewModel mViewModel;

    @BindView(R.id.recycler_view)
    RecyclerView mRecycleView;

    @BindView(R.id.empty_view)
    EmptyView mEmptyView;

    @BindView(R.id.post_images)
    ImageView createPost;


    private List<FindPost> mList = new ArrayList<>();
    private CommonAdapter<FindPost> mAdapter;

    public static FindFragment newInstance() {
        return new FindFragment();
    }

    @Override
    protected int getContentLayoutId() {
        return R.layout.find_fragment;
    }

    @Override
    protected void initWidget(View root) {
        super.initWidget(root);
        initView();
    }

    @Override
    protected void initData() {
        super.initData();
        getFindList();
    }

    @Override
    public void onResume() {
        super.onResume();
        getFindList();
    }

    private void initView() {
        mRecycleView.setLayoutManager(new LinearLayoutManager(getActivity()));
        mRecycleView.addItemDecoration(new DividerItemDecoration(getActivity(),
                DividerItemDecoration.VERTICAL));
        mAdapter = new CommonAdapter<>(mList, new CommonAdapter.OnBindDataListener<FindPost>() {
            @Override
            public void onBindViewHolder(FindPost model, CommonViewHolder viewHolder, int type, int position) {
                fillData(model, viewHolder);
                // 动态点赞
                digOrUndig(model, viewHolder);
                // 跳转评论

                // 跳转详情
                viewHolder.getView(R.id.posts).setOnClickListener(v -> {
                    Intent intent = new Intent(getActivity(), PostDetailActivity.class);
                    intent.putExtra("postId", model.getId());
                    startActivity(intent);
                });
                viewHolder.getView(R.id.comment_num).setOnClickListener(v -> {
                    Intent intent = new Intent(getActivity(), PostDetailActivity.class);
                    intent.putExtra("postId", model.getId());
                    startActivity(intent);
                });
            }

            @Override
            public int getLayoutId(int type) {
                return R.layout.find_post_item;
            }
        });
        mRecycleView.setAdapter(mAdapter);
        //监听列表滑动
        mRecycleView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
            }
        });
    }

    private void fillData(FindPost model, CommonViewHolder viewHolder) {
        CircleTextImage mCircleTextImage = viewHolder.getView(R.id.tag_avatar);
        AImageView mTrueAvatar = viewHolder.getView(R.id.tag_avatar_true);
        if(model != null && model.getAvatar() != null){
            mTrueAvatar.setVisibility(View.VISIBLE);
            mTrueAvatar.setImageUrl(model.getAvatar());
            mCircleTextImage.setVisibility(View.GONE);
        } else {
            // 用户名不为空展示文字头像
            if(model != null && model.getUsername() != null && model.getUsername().length() > 0){
                mCircleTextImage.setText4CircleImage(Utils.getName(model.getUsername()));
            }
        }

        viewHolder.setText(R.id.tag_title, model.getUsername() + " | " + model.getTrade() + " " + model.getPosition());
        viewHolder.setText(R.id.tag_desc, model.getLocation() +"  "+ model.getWorkingYears() + "年工作经验");
        if(TextUtils.isEmpty(model.getLocation()) || model.getWorkingYears() == null ){
            viewHolder.goneIfEmpty(R.id.tag_desc);
        }

        viewHolder.setText(R.id.post_text, model.getContent());
        if(model.getPictureList()!=null && model.getPictureList().size() > 0){
            viewHolder.setImageUrl(getActivity(), R.id.post_images, model.getPictureList().get(0));
        }else {
            viewHolder.goneIfEmpty(R.id.post_images);
        }
        viewHolder.setText(R.id.post_time, TimeUtils.calculate(model.getPublishTime()));
        // 开始喜欢
        if(model.getBoolLike()){
            viewHolder.setText(R.id.liked_num, String.valueOf(model.getLikeCount()));
            viewHolder.goneIfEmpty(R.id.like_num);
            viewHolder.show(R.id.liked_num);
        } else {
            viewHolder.setText(R.id.like_num, String.valueOf(model.getLikeCount()));
            viewHolder.goneIfEmpty(R.id.liked_num);
            viewHolder.show(R.id.like_num);
        }
        viewHolder.setText(R.id.comment_num, String.valueOf(model.getCommentCount()));
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
    }



    private void getFindList() {
        RemoteService service = Network.remote();
        Call<RspModel<PageList<FindPost>>> call = service.postPage(1,1000);
        call.enqueue(new Callback<RspModel<PageList<FindPost>>>() {
            @Override
            public void onResponse(Call<RspModel<PageList<FindPost>>> call, Response<RspModel<PageList<FindPost>>> response) {
                RspModel<PageList<FindPost>> body = response.body();
                /*if(response.code() == 401){
                    Log.e(TAG, "尚未登录");
                    AccountActivity.show(getContext());
                    return;
                }*/
                if(body !=null && body.success()){
                    PageList<FindPost> posts = body.getData();
                    String rspString = SimpleJsonTool.toJson(posts); Log.e(TAG, rspString);
                    if(posts.getTotal() == 0) {
                        mRecycleView.setVisibility(View.GONE);
                        mEmptyView.setVisibility(View.VISIBLE);
                    } else {
                        mRecycleView.setVisibility(View.VISIBLE);
                        mEmptyView.setVisibility(View.GONE);
                        if (mList.size() > 0) {
                            mList.clear();
                        }
                        mList.addAll(posts.getRecords());
                        mAdapter.notifyDataSetChanged();
                        Log.e(TAG, "find list:" + mList.toString());
                    }
                }else {
                    Log.e(TAG, "request fail: " + response.code());
                }
            }

            @Override
            public void onFailure(Call<RspModel<PageList<FindPost>>> call, Throwable t) {
                Log.e(TAG, "request fail: onFailure");
            }
        });
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mViewModel = ViewModelProviders.of(this).get(FindViewModel.class);
        // TODO: Use the ViewModel
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (hidden) {
            if (!CommonUtils.isEmpty(mList)) {
                // BaseApplication.showToast("获取发布");
                getFindList();
            }
        }
    }

    // 动态点赞
    protected void digPost(String postId){
        RemoteService service = Network.remote();
        Call<RspModel<Boolean>> call = service.postLike(postId);
        call.enqueue(new Callback<RspModel<Boolean>>() {
            @Override
            public void onResponse(Call<RspModel<Boolean>> call, Response<RspModel<Boolean>> response) {

                RspModel<Boolean> body = response.body();
                /*if(response.code() == 401){
                    Log.e(TAG, "尚未登录");
                    AccountActivity.show(getActivity());
                    return;
                }*/
                if(body !=null && body.success()){
                    // BaseApplication.showToast("点赞成功");
                }else {
                    Log.e(TAG, "request fail");
                }
            }

            @Override
            public void onFailure(Call<RspModel<Boolean>> call, Throwable t) {
                Log.e(TAG, t.getMessage());
            }
        });
    }

    // 取消动态点赞
    protected void unDigPost(String postId){
        RemoteService service = Network.remote();
        Call<RspModel<Boolean>> call = service.postUnlike(postId);
        call.enqueue(new Callback<RspModel<Boolean>>() {
            @Override
            public void onResponse(Call<RspModel<Boolean>> call, Response<RspModel<Boolean>> response) {
                RspModel<Boolean> body = response.body();
                /*if(response.code() == 401){
                    Log.e(TAG, "尚未登录");
                    AccountActivity.show(getActivity());
                    return;
                }*/
                if(body !=null && body.success()){
                    // BaseApplication.showToast("取消点赞成功");
                }else {
                    Log.e(TAG, "request fail");
                }
            }

            @Override
            public void onFailure(Call<RspModel<Boolean>> call, Throwable t) {
                Log.e(TAG, t.getMessage());
            }
        });
    }

    protected void digOrUndig(FindPost model, CommonViewHolder viewHolder) {
        // 点赞
        viewHolder.getView(R.id.like_num).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                digPost(model.getId());
                viewHolder.goneIfEmpty(R.id.like_num);
                viewHolder.show(R.id.liked_num);
                int digNum = model.getBoolLike() ? model.getLikeCount() : model.getLikeCount()+1;
                // 开始喜欢 点赞 不变， 开始不喜欢 点赞+1
                viewHolder.setText(R.id.liked_num, String.valueOf(digNum));
            }
        });
        // 取消点赞
        viewHolder.getView(R.id.liked_num).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                unDigPost(model.getId());
                viewHolder.goneIfEmpty(R.id.liked_num);
                viewHolder.show(R.id.like_num);
                int digNum = model.getBoolLike() ? model.getLikeCount() - 1 : model.getLikeCount();
                // 开始喜欢 取消点赞 -1， 开始不喜欢 取消点赞不变
                viewHolder.setText(R.id.like_num, String.valueOf(digNum));

            }
        });
    }

    @OnClick(R.id.post_images)
    void createPost(){
        startActivity(new Intent(getActivity(), CreatePostActivity.class));
    }


}